/*
 * Copyright (c) 2012 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.libermundi.theorcs.chronicles.tapestry.pages.admin.perso;

import java.util.List;

import org.apache.tapestry5.Block;
import org.apache.tapestry5.SelectModel;
import org.apache.tapestry5.ValueEncoder;
import org.apache.tapestry5.alerts.AlertManager;
import org.apache.tapestry5.annotations.OnEvent;
import org.apache.tapestry5.annotations.Persist;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.annotations.SessionState;
import org.apache.tapestry5.ioc.Messages;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.services.ValueEncoderFactory;
import org.libermundi.theorcs.chronicles.dto.ChronicleSettings;
import org.libermundi.theorcs.chronicles.model.Persona;
import org.libermundi.theorcs.chronicles.services.ChronicleManager;
import org.libermundi.theorcs.chronicles.services.PersonaManager;
import org.libermundi.theorcs.chronicles.tapestry.base.ChronicleAdminPage;
import org.libermundi.theorcs.core.model.Gender;
import org.libermundi.theorcs.core.tapestry.util.GenericSelectModel;
import org.libermundi.theorcs.security.model.User;

import com.google.common.base.Strings;

/**
 * @author Martin Papy
 *
 */
public class Main extends ChronicleAdminPage {
	public static final String PAGE_ID="chronicles.pages.admin.perso.infos";
	
	@Inject
	private Block _notification;
	
	@Inject
	private Block _displayPersona;

	@Inject
	private Block _editPersona;
	
	@Inject
	private Block _empty;	
	
	@Inject
	private Messages _messages;
	
	@SuppressWarnings("rawtypes")
	@Inject
	private ValueEncoderFactory _valueEncoderFactory;
	
	@Inject
	private PersonaManager _personaManager;
	
	@Inject
	private ChronicleManager _chronicleManager;
	
	@SessionState
	private ChronicleSettings _chronicleSettings;
	
	@Persist
	@Property
	private Persona _selectedPersona;
	
	@Inject
	private AlertManager _alertManager;
	
	@Persist
	private boolean _editMode;
	
	public Block getPersonaDetails() {
		if(_selectedPersona == null) {
			return _empty;
		}
		
		if(_editMode) {
			return _editPersona;
		}
		
		return _displayPersona;
	}
	
	public String getPersonaDescription(){
		return notEmptyString(_selectedPersona.getDescription());
	}
	
	public String getPersonaBackground(){
		return notEmptyString(_selectedPersona.getBackground());
	}
	
	public String getPersonaHiddenInfos(){
		return notEmptyString(_selectedPersona.getHiddenInfos());
	}
	
	@SuppressWarnings("unchecked")
	public ValueEncoder<User> getUserEncoder(){
		return _valueEncoderFactory.create(User.class);
	}
	
	public SelectModel getUserModel() {
		List<User> users = _chronicleManager.getUsersByChronicle(_chronicleSettings.getChronicle());
		return new GenericSelectModel<User,Long>(users);
	}
	public String getGender(){
		String genderKey = Gender.class.getSimpleName() + "." + _selectedPersona.getGender().name();
		if(_messages.contains(genderKey)) {
			return _messages.get(genderKey);
		}
		return _selectedPersona.getGender().name();
	}
	
	public String getDeleteWarningMessage() {
		return _messages.format("chronicles.admin.persona.management.delete.confirm.message", _selectedPersona.getName());
	}
	
	/* (non-Javadoc)
	 * @see org.libermundi.theorcs.core.tapestry.BasePage#getPageId()
	 */
	@Override
	public String getPageId() {
		return PAGE_ID;
	}
	
	@OnEvent("success")
	public void savePerso(){
		_personaManager.save(_selectedPersona);
		_editMode = Boolean.FALSE;
	}

	@OnEvent("valueChanged")
	public Block selectPerso(Persona perso){
		_editMode = Boolean.FALSE; // Back to View Mode by default
		
		// The new Perso is actually loaded in the setSelected method 
		// that is called after this Event
		if(perso == null) {
			return _empty;
		}
		return _displayPersona;
	}
	
	@OnEvent("deletePersona")
	public void deletePersona() {
		if(_selectedPersona.equals(_chronicleSettings.getPersona())){
			_alertManager.error(_messages.get("chronicles.admin.persona.management.delete.failed"));
		} else {
			_alertManager.success(_messages.get("chronicles.admin.persona.management.delete.success"));
			_personaManager.delete(_selectedPersona);
			_selectedPersona = null;
		}
	}
	
	@OnEvent("switchMode")
	public void switchMode(){
		_editMode = !_editMode;
	}
	
	private String notEmptyString(String input){
		if(Strings.isNullOrEmpty(input)){
			return "<em>" + _messages.get("chronicles.undefined") + "</em>";
		}
		return input;
	}
}
